from django.conf import settings
# from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth.backends import BaseBackend

class JwtQueryParamsAuthentication(BaseBackend):

    def authenticate(self, request):
        # 获取token并判断token的合法性
        token = request.query_params.get('token')
        salt = settings.SECRET_KEY
        import jwt
        from jwt import exceptions
        try:
            payload = jwt.decode(token, salt, True)
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({'code': 1003, 'error': 'token已失效'})
        except jwt.DecodeError:
            raise AuthenticationFailed({'code': 1003, 'error': 'token认证失效'})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({'code': 1003, 'error': '非法的token'})
        return (payload, token)
